package com.mewpipe.dao.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;

import com.mewpipe.dao.LnkUserLikeDao;
import com.mewpipe.entity.LnkUserLike;

public class JpaLnkUserLikeDao implements LnkUserLikeDao{

private EntityManagerFactory emf;
	


	public JpaLnkUserLikeDao(EntityManagerFactory emf) {
				this.emf = emf;
			}



	@Override
	public void addLink(long IdUser, long IdObject, boolean TypeLike,boolean TypeObject) {
		
		EntityManager em = emf.createEntityManager();
		LnkUserLike newlink = new LnkUserLike(IdUser,IdObject,TypeLike,TypeObject);//cf Entity
		
		
		try {
			em.getTransaction().begin();
			em.persist(newlink);
			em.getTransaction().commit();
			
		} 
		
		
		finally {
			if(em.getTransaction().isActive()) em.getTransaction().rollback();
			em.close();
	
	}
	}

	
	
	
	@SuppressWarnings("unchecked")
	@Override
	public boolean CheckVote(long IdUser, long IdObject) {
		EntityManager em = emf.createEntityManager();
		Query query= em.createQuery("FROM LnkUserLike l where typeObject=0 and idObject="+IdObject+" and idUser="+IdUser);
		List<LnkUserLike> tmp=null ;
		boolean return_bool= false;
		try {
			
			tmp = query.getResultList();
			 if(tmp.isEmpty()){
					return_bool =false;
				}
				else{
					return_bool =true;
				}
			
		}catch(Exception e )
		{
			
			
		}
		finally {
			
			em.close();
			
		}
		return return_bool;
		
	}
	@SuppressWarnings("unchecked")
	@Override
	public boolean CheckVoteCom(long IdUser, long IdObject) {
		EntityManager em = emf.createEntityManager();
		Query query= em.createQuery("FROM LnkUserLike l where typeObject=1 and idObject="+IdObject+" and idUser="+IdUser);
		List<LnkUserLike> tmp=null ;
		boolean return_bool= false;
		try {
			
			tmp = query.getResultList();
			 if(tmp.isEmpty()){
					return_bool =false;
				}
				else{
					return_bool =true;
				}
			
		}catch(Exception e )
		{
			
			
		}
		finally {
			
			em.close();
			
		}
		return return_bool;
		
	}




	

}
